<template>
  <div class="wrapper-upload-panel" ref="wppRef">
    <template v-if="props.type === 'image'">
      <div
        class="cover-box draggable-item"
        v-for="(item, index) in dataList"
        :key="index + '|' + item"
      >
        <PipeImage class="cover" :url="item" />
        <div class="mark">
          <span class="iconbox" @click="handleClickRowView(item)">
            <el-icon><zoom-in /></el-icon>
          </span>
          <span class="iconbox" @click="handleClickRowDel(index)" v-if="isEdit">
            <el-icon><Delete /></el-icon>
          </span>
        </div>
      </div>
    </template>

    <template v-if="props.type === 'video'">
      <div class="cover-box" v-for="(item, index) in dataList" :key="index">
        <video
          class="cover"
          :src="formatWebUrl(item)"
          :controls="false"
        ></video>
        <div class="mark">
          <span class="iconbox" @click="handleClickRowViewVideo(item)">
            <el-icon><zoom-in /></el-icon>
          </span>
          <span class="iconbox" @click="handleClickRowDel(index)" v-if="isEdit">
            <el-icon><Delete /></el-icon>
          </span>
        </div>
      </div>
    </template>

    <div class="upload-btn" v-if="isShowUploadBtn" @click="handleClickUpload">
      <el-icon><Plus /></el-icon>
    </div>
  </div>

  <el-dialog
    v-model="drawerOpts.visible"
    :width="drawerOpts.size"
    append-to-body
    align-center
    destroy-on-close
  >
    <img
      class="wrapper-upload-panel-preview-image"
      :src="formatWebUrl(drawerOpts.data.url)"
      alt="Preview Image"
      v-if="props.type === 'image'"
    />
    <iframe
      class="wrapper-upload-panel-preview-iframe"
      :src="formatWebUrl(drawerOpts.data.url)"
      frameborder="0"
      v-if="props.type === 'video'"
    ></iframe>
  </el-dialog>

  <UploadModal
    v-model:visible="dialogUploadModal.visible"
    :list="dataList"
    :type="type"
    :max="hasMaxLimit"
    :compress-size="props.compressSize"
    @on-complete="dialogUploadModal.complete"
  />
</template>

<script setup lang="ts">
import { InitDrawerOpts, transformPromise } from '@/utils/common';
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue';
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { ElMessageBox } from 'element-plus';
import type { Action } from 'element-plus';
import UploadModal from '@/components/UploadModal.vue';
import { formatWebUrl } from '@/utils/util';
import Sortable from 'sortablejs';

// 弹窗
const drawerOpts = reactive(InitDrawerOpts<{ url: string }>({ size: 'auto' }));

// 弹窗
const dialogUploadModal = reactive(InitDrawerOpts<{ url: string }>());

const props = defineProps({
  // 控件类型
  type: {
    type: String,
    default: 'image',
    validator(value: string) {
      return ['image', 'video'].includes(value);
    }
  },

  // 带“英文逗号”间隔的字符串
  modelValue: {
    type: String,
    default: ''
  },

  // 最大上传数量
  max: {
    type: Number,
    default: 1
  },

  // 是否可编辑
  isEdit: {
    type: Boolean,
    default: true
  },

  // 压缩后的质量大小（KB），不传则不压缩
  compressSize: {
    type: Number,
    default: 0
  }

  // // 预览模式
  // isView: {}
});

// emits
const emits = defineEmits(['update:modelValue']);

const dataList = ref<string[]>([]);
watch(
  () => props.modelValue,
  (val) => {
    dataList.value = val ? val.split(',') : [];
    // console.log('props.modelValue', [...dataList.value]);
  },
  {
    immediate: true
  }
);

// 计算剩余数量
const hasMaxLimit = computed(() => props.max - dataList.value.length);

// 是否显示上传按钮
const isShowUploadBtn = computed(() => {
  return props.isEdit && hasMaxLimit.value > 0;
});

// 查看大图
const handleClickRowView = (url: string) => {
  drawerOpts.data.url = url;
  drawerOpts.visible = true;
};

// 查看视频
const handleClickRowViewVideo = (url: string) => {
  // console.log("handleClickRowViewVideo", url);
  // window.open(url);

  drawerOpts.data.url = url;
  drawerOpts.visible = true;
};

// 删除
const handleClickRowDel = (index: number) => {
  ElMessageBox.confirm('是否删除此图片？', '删除图片', {
    type: 'warning',
    showClose: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    callback: (action: Action) => {
      if (action === 'confirm') {
        dataList.value.splice(index, 1);
        emits('update:modelValue', dataList.value.join(','));
      }
    }
  });
};

// 上传
const handleClickUpload = async () => {
  dialogUploadModal.visible = true;
  const res = await transformPromise<string[]>(dialogUploadModal);
  dataList.value = res.result;
  emits('update:modelValue', dataList.value.join(','));
};

const wppRef = ref<HTMLElement>();
const initSortable = () => {
  if (props.type !== 'image') return;

  const el = wppRef.value;
  Sortable.create(el!, {
    // 指定哪些元素可拖动
    draggable: '.draggable-item',
    filter: '.upload-btn',

    onEnd: (opts: any) => {
      // // 业务逻辑：根据下标查找item，然后移动数据位置
      // console.log('拖拽前的下标', opts.oldIndex);
      // console.log('拖拽后的下标', opts.newIndex);
      // console.log('拖拽后的列表', opts.to);

      // 克隆数据
      const list = [...dataList.value];

      // 从数组中截取项
      const item = list.splice(opts.oldIndex, 1)?.[0];
      // console.log('本次移动的目标：', item);

      // 插入到新位置
      list.splice(opts.newIndex, 0, item);
      // console.log('移动后的数据：', list);

      // 更新数据
      emits('update:modelValue', list.join(','));
    }
  });
};

onMounted(() => {
  initSortable();
});
</script>

<style lang="scss" scoped>
.wrapper-upload-panel {
  display: flex;
  flex-wrap: wrap;
  // margin-right: -8px;
  margin-bottom: -8px;

  .cover-box {
    // flex: 0 0 80px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 80px;
    height: 80px;
    border: 1px solid #cdd0d6;
    border-radius: 8px;
    overflow: hidden;
    position: relative;
    margin-right: 8px;
    margin-bottom: 8px;

    .cover {
      display: block;
      max-width: 100%;
      max-height: auto;
    }

    .mark {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      position: absolute;
      z-index: 1;
      background-color: rgba(0, 0, 0, 0.64);
      opacity: 0;
      transition: opacity 0.16s;

      &:hover {
        opacity: 1;
      }

      .iconbox {
        margin-right: 8px;
        cursor: pointer;
        font-size: 20px;
        color: #fff;
        line-height: initial;

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }

  .draggable-item {
    cursor: move;
  }

  .upload-btn {
    // flex: 0 0 80px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 80px;
    height: 80px;
    border: 1px dashed #cdd0d6;
    border-radius: 8px;
    cursor: pointer;
    font-size: 20px;
    margin-right: 8px;
    margin-bottom: 8px;

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.wrapper-upload-panel-preview-image {
  display: block;
  max-width: 100%;
  margin: 0 auto;
}

.wrapper-upload-panel-preview-iframe {
  display: block;
  width: 1080px;
  height: 720px;
  border: none;
  overflow: hidden;
}
</style>
